<?php

namespace app\admin\controller;

use app\common\model\AdminUser;
use think\Controller;
use utils\Auth;
use utils\Result;
use utils\Upload;

class Common extends Controller
{
    public function __construct()
    {
        parent::__construct();
        if (empty(session('aid'))) {
            header('location:' . url('logins/index'));
            exit;
        }
    }

    public function getInfo()
    {
        $id = session('aid');

        $info = AdminUser::get($id);

        return $info;

    }

    /**
     * 权限严重
     * @param bool $location
     */
    protected function AuthCheck($location = true)
    {
        if (!Auth::check() && $location) {
            $this->error('您的权限不足，无法对该界面进行操作,请返回或者关闭当前页面');
            exit;
        } else if (!Auth::check() && $location == false) {
            return Result::error('您的权限不足，无法进行操作');
        }
        return true;
    }

    /**
     * 上传图片
     * @return \utils\Result
     */
    public function uploadImages()
    {
        return Upload::createImages();
    }

    /**
     * 将菜单转换为一维数组
     * @param $menu
     * @param int $id
     * @param int $level
     * @return array
     */
    protected function menulist($menu, $id = 0, $level = 0)
    {
        static $menus = array();
        foreach ($menu as $value) {
            if ($value['parent_id'] == $id) {
                $value['level'] = $level + 1;
                if ($level == 0) {
                    $value['str'] = str_repeat('', $value['level']);
                } elseif ($level == 2) {
                    $value['str'] = '&nbsp;&nbsp;&nbsp;&nbsp;' . '└ ';
                } elseif ($level == 3) {
                    $value['str'] = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . '└ ';
                } else {
                    $value['str'] = '&nbsp;&nbsp;' . '└ ';
                }
                $menus[] = $value;
                $this->menulist($menu, $value['id'], $value['level']);
            }
        }
        return $menus;
    }

    /**
     * 组装多维子集
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    protected function recursive_make_tree($list, $pk = 'id', $pid = 'parent_id', $child = '_child', $root = 0)
    {
        $tree = [];
        foreach ($list as $key => $val) {
            if ($val[$pid] == $root) {
                //获取当前$pid所有子类
                unset($list[$key]);
                if (!empty($list)) {
                    $child = $this->recursive_make_tree($list, $pk, $pid, $child, $val[$pk]);
                    if (!empty($child)) {
                        $val['_child'] = $child;
                    } else {
                        $val['_child'] = null;
                    }
                }
                $tree[] = $val;
            }
        }
        return $tree;
    }

}